<?php
namespace frontend\models;

use common\models\User;
use common\WuMing;
use yii\base\ErrorException;
use yii\base\Model;
use Yii;
use common\models\Post;

/**
 * Post form
 */
class ArticleForm extends Model
{
    public $title;
    public $cid1;
    public $content;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title'], 'required','message'=>'请输入标题'],
            [['content'], 'required','message'=>'请输入内容'],
            [['cid1'], 'required','message'=>'请选择分类'],
            [['content'], 'string'],
            [['cid1'], 'integer'],
            [['title'], 'string', 'max' => 255],
        ];
    }


    public function createPost()
    {
        if ($this->validate()) {
            $user = User::findOne(Yii::$app->user->id);
            //登录用户发帖45秒间隔限制
//            if (time() - $user->last_post < 45) {
//                return false;
//            }
            $user->last_post = time();
            $user->save();
            //保存用的发布的文章
            $post = new Post();
            $post->title = htmlspecialchars($this->title);
            $post->content = $this->content;
            $post->cate_id = $this->cid1;
            $post->user_id = Yii::$app->user->id;
            //测试方便 发布时改为0
            $post->status = 1;
            $post->ip_address = Yii::$app->request->getUserIP();
            $post->signature = $user->signature;
            $post->nickname = $user->nickname;
            $post->img = $user->img;
            $post->create_at = time();
            $post->type =1;
         //   WuMing::dd($post);die;
            //如果发布成功  跳转到帖子详情页
            if ($post->save()) {
                return $post;
            }
        }
        return false;
    }
}
